﻿using System.Linq;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using Avalonia.ReactiveUI;
using MilkTeaMachine.OfflineClient.Models;
using MilkTeaMachine.OfflineClient.Utils;
using MilkTeaMachine.OfflineClient.ViewModels;
using ReactiveUI;

namespace MilkTeaMachine.OfflineClient.Views;

public partial class FormulaSaveOrUpdateUserControl : ReactiveUserControl<FormulaSaveOrUpdateViewModel>
{
    public FormulaSaveOrUpdateViewModel ViewModelLocal => ViewModel!;

    public FormulaSaveOrUpdateUserControl()
    {
        AvaloniaXamlLoader.Load(this);
        this.WhenActivated(_ => { });
    }

    private void SelectingItemsControl_OnSelectionChanged(object? sender, SelectionChangedEventArgs e)
    {
        var comboBox = (ComboBox)sender!;
        //切换
        if (e.AddedItems.Count != 0 &&
            e.RemovedItems.Count != 0 &&
            e.AddedItems[0] is IngredientAndWeightVo toAdd &&
            e.RemovedItems[0] is IngredientAndWeightVo)
        {
            int index;
            if (toAdd.IngredientId == -1)
            {
                index = comboBox.TabIndex;
                ViewModelLocal.FormulaDetail.IngredientAndWeightList[index] = toAdd;
                return;
            }
            var selected = ViewModelLocal.FormulaDetail.IngredientAndWeightList.FirstOrDefault(vo =>
                vo.IngredientId == toAdd.IngredientId);
            if (selected is not null)
            {
                comboBox.SelectedValue = new IngredientAndWeightVo();
                MessageBoxUtil.GetBox("该原料已添加过，请勿重复添加").ShowWindowAsync();
            }

            index = comboBox.TabIndex;
            ViewModelLocal.FormulaDetail.IngredientAndWeightList[index] =
                (IngredientAndWeightVo)comboBox.SelectedValue!;
        }
    }
}